import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI, {Message} from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios'
import VueAxios from 'vue-axios'
import SnowflakeId from "snowflake-id"
import JsonViewer from 'vue-json-viewer';
import VueAMap from 'vue-amap';
Vue.use(VueAMap);


Vue.use(JsonViewer);
Vue.use(VueAxios, axios)
Vue.use(ElementUI);
Vue.config.productionTip = false
Vue.prototype.$httpBlock = axios;
Vue.prototype.$httpUrl = "http://192.168.126.130:8080/route";
Vue.prototype.$snowFlakeId = SnowflakeId;

//vue前端代理
axios.defaults.baseURL='http://localhost:9999'

//请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  const uuid=sessionStorage.getItem("uuid")
  const token=localStorage.getItem("token")
  if(uuid) {
    config.headers['uuid'] = uuid
  }
  if(token){
    config.headers['token']=token
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

//导航守卫
router.beforeEach((to, from, next) => {
  const token=localStorage.getItem("token")
  if (to.name !== 'login' && !token) {
    next({ name: 'login' })
    Message.error("请先登录后再进行操作")
  }
  else next()
})

//动态路由
router.beforeEach((to, from, next) => {
  if (router.getRoutes().length == 3) {//index.js 默认配置了两个静态路由 ,则需要执行动态路由
    axios.get('/menu/menu/menuList').then(res => {
      if (res.data.state == 0) {
        let menuData = res.data.data;//获取一级菜单
        menuData.forEach(menu => {
              if (menu.hasOwnProperty("children")) {
                menu.children.forEach(subMenu => { //遍历二级菜单
                  let newRouter = {
                    name: subMenu.name,
                    path: subMenu.path
                  }
                  newRouter.component = () => import( './views/' + subMenu.component + '.vue');
                  router.options.routes[0].children.push(newRouter);
                })
              }
            }
        )
        router.addRoutes(router.options.routes);
      } else {
        next({name: 'login'})
      }

    })

  }
  next();
})


// 高德地图
// VueAMap.initAMapApiLoader({
//   key: '3e5db00ff818adf2b2e2f600f0a72608',
//   v: '1.4.4'
// });

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')



